#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

// 发送FTP命令并接收响应
bool sendCommand(int sockfd, const std::string& command, std::string& response) 
{
    char buffer[1024] = {0};
    
    // 发送命令
    if (send(sockfd, command.c_str(), command.length(), 0) < 0) 
    {
        std::cerr << "发送命令失败" << std::endl;
        return false;
    }
    
    // 接收响应
    memset(buffer, 0, sizeof(buffer));
    if (recv(sockfd, buffer, sizeof(buffer), 0) < 0) 
    {
        std::cerr << "接收响应失败" << std::endl;
        return false;
    }
    response = buffer;
    return true;
}

int main() 
{
    int controlSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (controlSocket < 0) 
    {
        std::cerr << "创建套接字失败" << std::endl;
        return -1;
    }
    
    // 连接FTP服务器
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(21);
    serverAddr.sin_addr.s_addr = inet_addr("ftp.example.com");
    
    if (connect(controlSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) 
    {
        std::cerr << "连接失败" << std::endl;
        return -1;
    }
    
    // 接收欢迎消息
    std::string response;
    if (!sendCommand(controlSocket, "", response)) 
    {
        return -1;
    }
    std::cout << "欢迎消息: " << response << std::endl;
    
    // 登录
    if (!sendCommand(controlSocket, "USER user\r\n", response)) return -1;
    std::cout << "USER响应: " << response << std::endl;
    
    if (!sendCommand(controlSocket, "PASS pass\r\n", response)) return -1;
    std::cout << "PASS响应: " << response << std::endl;
    
    close(controlSocket);
    return 0;
}